package com.util;

import com.dao.UserDao;
import com.models.User;
import com.dao.impl.UserDaoImpl;

/**
 * Created by TimeLiar on 2015/9/17.
 * All Hail The King !!!!!!
 * Singleton
 */
public enum Session {
    @SuppressWarnings("unused")
    INSTANCE;
    private static User current_user;
    private static UserDao userDao = new UserDaoImpl();
    /**
     * @param username User name
     * @param password User password
     */
    public static void login(String username,String password) throws Error{
        User user = userDao.getUser(username);
        if(user != null){
            if(user.getPassword() != null && user.getPassword().equals(MD5.getMD5Code(password))){
                current_user = user;
                return;
            }
        }
        throw new Error(username , password == null);
    }

    /**
     *
     * @return isLogin
     */
    @SuppressWarnings("unused")
    public static boolean isLogin(){
        return current_user != null;
    }

    /**
     * logout
     */
    @SuppressWarnings("unused")
    public static void logout(){
        current_user = null;
    }

    @SuppressWarnings("unused")
    public static User getCurrent_user() {
        return current_user;
    }

    @SuppressWarnings("unused")
    public static boolean havePermission(String entity , String permission){
        return current_user.getPermission().get(entity==null?"*":entity).contains("*")
                || current_user.getPermission().get(entity==null?"*":entity).contains(permission);
    }
}
